package com.imooc.controller;

import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UserBO;
import com.imooc.service.UserService;
import com.imooc.service.impl.UserServiceImpl;
import com.imooc.utils.IMOOCJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@Api(value = "注册登录" , tags = {"用于注册登录相关接口"})  //阐述接口
@RestController
@RequestMapping("passport")
public class PassportController {

    private UserServiceImpl userService;

    public PassportController(UserServiceImpl userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "用户名是否存在",notes = "用户名是否存在" ,httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public IMOOCJSONResult usernameIsExist(@RequestParam  @ApiParam(value = "用户名") String username){
        //入参不能为空
        if(StringUtils.isBlank(username)){
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        //查找用户名是否存在
        if(userService.queryUserIsExist(username)){
            return   IMOOCJSONResult.errorMsg("用户名已存在");
        }
        return IMOOCJSONResult.ok();
    }

    @ApiOperation(value = "用户注册",notes = "用户注册" ,httpMethod = "POST")
    @PostMapping("/regist")
    public IMOOCJSONResult regist(@RequestBody UserBO userBO){
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPassword = userBO.getConfirmPassword();
        // 用户名和密码必须不为空
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)
                || StringUtils.isBlank(confirmPassword)){
            return  IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        //用户名不存在
        if(userService.queryUserIsExist(username)){
            return   IMOOCJSONResult.errorMsg("用户名已存在");
        }
        //密码长度不能少于6位
        if(password.length() < 6){
            return  IMOOCJSONResult.errorMsg("密码长度不能小于6");
        }
        //密码是否正确
        if(!password.equals(confirmPassword)){
            return  IMOOCJSONResult.errorMsg("两次密码输入不一致");
        }
        //注册
        Users user = userService.createUser(userBO);
        return IMOOCJSONResult.ok(user);
    }

}
